#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_MAX_SIZE (2*1024)
#define LINE_MAX_LENTH (128)
#define MAX_ROW (100)

int readlines(char *dsc[], const char * buf, int bufSize);
void freeStrlines(char* dsc[], int lineLenth);

int main(int argc, char* argv[]) {
    char* filename = "/proc/meminfo";
    int fd = open(filename, O_RDONLY);
    if (-1 == fd) {
        printf("cannot open file: %s!\n", filename);
        return 0;
    }

    char* buf = (char*)malloc(BUF_MAX_SIZE);
    int bufsize = read(fd, buf, BUF_MAX_SIZE);
    printf("%d!\n", (int)strlen("MemFree:          637884 kB"));
    printf("bufsize: %d!\n", bufsize);

    char* datas[MAX_ROW];
    memset(datas, 0, sizeof(MAX_ROW));

    int lines = readlines(datas, buf, bufsize);

    if (NULL == datas) {
        printf("datas is NULL");
    }
    else {
        int i = 0;
        while (i < lines) {
            printf("%02d. %s\n", i + 1, datas[i]);
            ++i;
        }
    }

    freeStrlines(datas, lines);
    free(buf);
    close(fd);
    return 0;
}

int readlines(char *dsc[], const char* buf, int bufSize)
{
    if ((NULL == buf)
         || (0 >= bufSize)) {
        printf("readlines failed, buf:%p, size:%d!\n", buf, bufSize);
        return 0;
    }

    int row = 0;
    int col = 0;
    char ch;
    int readedSize = 0;

    dsc[row] = (char*)malloc(LINE_MAX_LENTH);
    memset(dsc[row], 0, LINE_MAX_LENTH);

    while ((readedSize < bufSize) && (row < MAX_ROW)) {
       ch = *buf;
       if ('\0' == ch) {
           ++row;
           break;
       }
       if (('\n' == ch)
            || (col >= LINE_MAX_LENTH)) {
            ++row;
            col = 0;

            dsc[row] = (char*)malloc(LINE_MAX_LENTH);
            memset(dsc[row], 0, LINE_MAX_LENTH);
       }
       else {
           dsc[row][col] = ch;
           ++col;
       }
       ++buf;
       ++readedSize;
    }
    return row;
}

void freeStrlines(char* dsc[], int lineLenth)
{
    if (NULL == dsc) {
        return;
    }
    int row = 0;
    while (row < lineLenth) {
        if (NULL != dsc[row]) {
            free(dsc[row]);
        }
        ++row;
    }
}
